<!--
 * @Description: 新增/编辑
 * @Author: Boide
 * @Date: 2022-02-13 12:06:39
 * @LastEditors: guiyi@hongyi.tech
 * @LastEditTime: 2022-02-18 11:57:34
-->
<template>
	<el-card class="box-card">
    <el-button v-has-permi="['/wx/menu/postAddWxMenu']" class="mb20" type="primary" @click="addMenu();">添加一级菜单</el-button>
    <el-button class="mb20" type="primary" @click="goBack">返回</el-button>
		<el-row :gutter="20">
			<el-col :span="16" :offset="0">
				<el-card class="box-card">
					<el-table :key="tableKey" :data="menuList" border row-key="id" stripe :tree-props="{children: 'children'}">
						<el-table-column prop="name" label="菜单名称" align="left" show-overflow-tooltip width="160">
							<template slot-scope="{row}">
								<span :style="{'padding-left': row.children&&row.children.length<1? '24px':0}">{{row.name}}</span>
							</template>
						</el-table-column>
						<el-table-column label="内容" align="center" prop="nameTwo">
							<template slot-scope="{row}">
								<span>{{ contList[row.buttonType] }}</span>
							</template>
						</el-table-column>
						<el-table-column label="操作" align="right" class-name="small-padding fixed-width" width="260">
							<template slot-scope="{row}">
								<el-button v-if="row.buttonType==='drow_box'" v-has-permi="['/wx/menu/postAddWxMenu']" type="text" @click="addMenu(row, 2)">添加二级菜单</el-button>
								<el-button v-if="row.moveUp===1" v-has-permi="['/wx/menu/postWxMenuMove']" type="text" @click="handleMove(row.id, -1)">上移</el-button>
								<el-button v-if="row.moveDown===1" v-has-permi="['/wx/menu/postWxMenuMove']" type="text" @click="handleMove(row.id, 1)">下移</el-button>
								<el-button v-has-permi="['/wx/menu/postUpdateWxMenu']" type="text" @click="addMenu(row)">编辑</el-button>
								<el-button v-has-permi="['/wx/menu/postDelWxMenu']" type="text" @click="handleDelete(row)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-card>
			</el-col>
			<el-col :span="8" :offset="0">
        <div class="phone-flex">
          <div class="phone" @click="closeShow">
            <div class="head">
              <i class="el-icon-arrow-left"></i>
              <span>菜单配置效果预览</span>
              <i class="el-icon-user"></i>
            </div>
            <div class="tab">
              <div class="icon">
                <i class="el-icon-s-unfold"></i>
              </div>
              <div class="flex-1">
                <div v-for="(item, i) in menuList" :key="i"
                  :class="{'pointer': item.children&&item.children.length}" class="flex-item"
                  @click.stop.prevent="tapSub(i)"
                  >
                  <i v-if="item.children&&item.children.length" class="el-icon-s-operation"></i>
                  <span>{{item.name}}</span>
                  <div v-show="item.children&&item.children.length&&item.show" class="children">
                    <div class="children-item" v-for="(sub, j) in item.children" :key="j">{{sub.name}}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
			</el-col>
		</el-row>
    <!-- 添加或修改菜单 -->
    <el-dialog :title="(formModel.id?'编辑':'新增')+'菜单'" :visible.sync="formVisible" width="760px" append-to-body>
      <el-form ref="formModel" :model="formModel" :rules="formModelRules" label-width="130px">
        <el-form-item :label="`菜单名称:`" prop="name">
          <el-input v-model.trim="formModel.name" style="width: 80%" clearable placeholder="请输入菜单名称" maxlength="12" />
        </el-form-item>
        <el-form-item :label="`菜单类型:`" prop="buttonType">
          <el-radio-group v-model="formModel.buttonType" :disabled="formModel.children&&formModel.children.length>=1" size="small" @change="$refs.formModel.clearValidate()">
            <template v-for="(val, key) in contList">
              <el-radio-button v-if="formModel.level===2&&key!=='drow_box'||formModel.level!==2" :key="key" :label="key">{{val}}</el-radio-button>
            </template>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="formModel.buttonType==='text'" :label="`文字消息内容:`" prop="textMsg">
          <el-input v-model.trim="formModel.textMsg" type="textarea" style="width: 80%" :autosize="{ minRows: 4, maxRows: 6}" clearable
            placeholder="请输入图文消息内容" maxlength="500" />
        </el-form-item>
        <el-form-item v-if="formModel.buttonType==='image'" :label="`图片消息内容:`" prop="imageMsg">
          <el-select v-model="formModel.imageMsg" placeholder="请选择">
            <el-option v-for="item in optionsList.filter(o => o.msgType==='image')" :key="item.id" :label="item.resourcesName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="formModel.buttonType==='image_text'" :label="`图文消息内容:`" prop="imageTextMsg">
          <el-select v-model="formModel.imageTextMsg" placeholder="请选择">
            <el-option v-for="item in optionsList.filter(o => o.msgType==='image_text')" :key="item.id" :label="item.resourcesName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="formModel.buttonType==='view'" :label="`跳转网页链接:`" prop="url">
          <el-input v-model.trim="formModel.url" style="width: 80%" clearable placeholder="请输入跳转网页链接" maxlength="200" />
        </el-form-item>
        <el-form-item v-if="formModel.buttonType==='miniprogram'" :label="`小程序Url:`" prop="url">
          <el-input v-model.trim="formModel.url" style="width: 80%" clearable placeholder="请输入小程序地址" maxlength="200" />
        </el-form-item>
        <el-form-item v-if="formModel.buttonType==='miniprogram'" :label="`小程序APPID:`" prop="appid">
          <el-input v-model.trim="formModel.appid" style="width: 80%" clearable placeholder="请输入小程序appid" maxlength="200" />
        </el-form-item>
        <el-form-item v-if="formModel.buttonType==='miniprogram'" :label="`小程序页面地址:`" prop="pagepath">
          <el-input v-model.trim="formModel.pagepath" style="width: 80%" clearable placeholder="请输入小程序页面地址" maxlength="200" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible=!formVisible;resetMenu;">取 消</el-button>
        <el-button :loading="submitLoading" type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
	</el-card>
</template>

<script>
import { getCustomMenuOneAndTow, editMenu, addMenu, deleteMenu, getImageTextList, postWxMenuMove } from '@/api/wechatService/menu'
export default {
  data () {
    return {
      id: '',
      tableKey: 0,
      optionsList: [],
      contList: {
        'drow_box': '下拉框类型',
        'text': '发送文字消息',
        'image': '发送图片消息',
        'image_text': '发送图文消息',
        'view': '跳转网页',
        'miniprogram': '跳转小程序'
      },
      menuList: [],
      submitLoading: false,
      formVisible: false,
      formModel: {
        buttonType: 'drow_box'
      },
      formModelRules: {
        name: [
          { required: true, message: "菜单名称不能为空", trigger: "blur" }
        ],
        buttonType: [
          { required: true, message: "菜单内容必选", trigger: "blur" }
        ],
        textMsg: [
          { required: true, message: "文字消息内容不能为空", trigger: "blur" }
        ],
        imageMsg: [
          { required: true, message: "图片消息内容必选", trigger: "blur" }
        ],
        imageTextMsg: [
          { required: true, message: "图文消息内容必选", trigger: "blur" }
        ],
        url: [
          { required: true, message: "url地址不能为空", trigger: "blur" }
        ],
        appid: [
          { required: true, message: "appid不能为空", trigger: "blur" }
        ],
        pagepath: [
          { required: true, message: "页面地址不能为空", trigger: "blur" }
        ],
      }
    }
  },
  mounted () {
    this.id = this.$route.params.id
    this.queryList()
    this.optionsListFn()
  },
  methods: {
    queryList() {
      getCustomMenuOneAndTow(this.id).then(res => {
        this.menuList = res.data || []
      })
    },
    // 查询标签list
    optionsListFn () {
      getImageTextList().then(res => {
        this.optionsList = res.data
      })
    },
    // 新增/编辑弹窗
    addMenu (menu, type = 1) {
      this.$set(this.formModel, 'parentMenu', this.id || 0)
      if (menu) {
        this.formModel = {...menu}
      }
      if (type===2){
        this.formModel = {
          buttonType: 'text',
          parentMenu: menu.id,
          level: 2
        }
      }
      this.formVisible = true
    },
    // 重置表单
    resetMenu () {
      this.formModel = {
        buttonType: 'drow_box'
      }
      this.resetForm("formModel")
    },
    // 上移/下移
    handleMove(id, move) {
      postWxMenuMove({ id, move }).then(() => {
        this.queryList()
      })
    },
    // 删除
    handleDelete ({id}) {
      this.$confirm('此操作将删除该菜单以及子菜单，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteMenu({id}).then(() => {
          this.$message.success('删除成功！')
          this.queryList()
        })
      })
    },
    // 新增/编辑
    submitForm () {
      this.submitLoading = true
      this.$refs["formModel"].validate(async valid => {
        if (valid) {
          try {
            let params = {...this.formModel}
            if (this.formModel.id) {
              await editMenu(params)
            } else {
              await addMenu(params)
            }
            this.queryList()
            this.resetMenu()
            this.formVisible = false
            this.submitLoading = false
          } catch (error) {
            this.submitLoading = false
          }
        } else {
          this.submitLoading = false
        }
      })
    },
    tapSub(i) {
      const list = {...this.menuList[i]}
      this.closeShow()
      if (!list.show) {
        list.show = true
        this.$set(this.menuList, i, list)
      }
    },
    closeShow() {
      this.menuList.forEach((o, i) => {
        if (o.show) {
          this.$set(this.menuList[i], 'show', false)
        }
      })
    },
    goBack () {
      this.$store.dispatch('tagsView/delView', this.$route);
      this.$router.go(-1)
    }
  }
}
</script>

<style lang="scss" scoped>
.box-card {
  position: relative;
  &.minh400 {
    min-height: 400px;
  }
  .phone-flex{
    display: flex;
    justify-content: center;
  }
  .phone{
    width: 375px;
    height: 667px;
    background: #EDEDED;
    position: relative;
    .head{
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 44px;
      font-size: 18px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 20px;
      border-bottom: 1px solid #ccc;
      i{
        font-size: 24px;
      }
    }
    .tab{
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 44px;
      font-size: 16px;
      display: flex;
      background: #F6F6F6;
      .icon{
        width: 44px;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        i{
          font-size: 24px;
        }
      }
      .flex-1{
        height: 100%;
        display: flex;
        flex: 1;
        padding: 8px 0;
        .flex-item{
          display: flex;
          justify-content: center;
          align-items: center;
          flex: 1;
          position: relative;
          i{
            font-size: 12px;
            margin-right: 3px;
          }
          &::after{
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            bottom: 0;
            width: 1px;
            background: #efefef;
          }
          &.pointer{
            cursor: pointer;
          }
          .children{
            position: absolute;
            bottom: 36px;
            width: 100%;
            max-width: 100px;
            left: 50%;
            transform: translateX(-50%);
            background: #FFFFFF;
            .children-item{
              width: 100%;
              height: 44px;
              display: flex;
              justify-content: center;
              align-items: center;
              border-bottom: 1px solid #ccc;
            }
          }
        }
      }
    }
  }
  .mb20{
    margin-bottom: 20px;
  }
}
</style>
